package com.sso.main.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author:LuJiaHong
 * @Date:2021/2/18~21:54:19
 * @Version 1.0
 */
@Controller
@RequestMapping("/view")
public class ViewController {
    @Autowired
    private RestTemplate restTemplate;
    private final String LOGIN_INFO_ADDRESS = "http://www.lujiahong.com:9000/login/info?token=";
    @GetMapping("/index")
    public String toIndex(@CookieValue(required = false,value = "TOKEN") Cookie cookie, HttpSession session){
        if(cookie!=null){
            String token = cookie.getValue();
            if(!StringUtils.isEmpty(token)) {
                //按token获取用户信息
                Map userInfo =  restTemplate.getForObject(LOGIN_INFO_ADDRESS + token, Map.class);
                System.out.println("=============>>>>>>>>"+userInfo);
                session.setAttribute("loginUser",userInfo);
            }
        }
        return "index";
    }
    @GetMapping("/exit")
    public String toExit(@CookieValue(required = false,value = "TOKEN") Cookie cookie, HttpServletResponse
            response,HttpSession session){
        if(cookie!=null){
            //登录过cookie对象不为空，设置最大生命为0，即cookie过期
            cookie.setMaxAge(0);
            //cookie在子系统间访问，要求域名相同
            cookie.setDomain("lujiahong.com");
            cookie.setPath("/");
            //移除存储的用户信息
            session.removeAttribute("loginUser");
            //响应到子系统
            response.addCookie(cookie);
        }
        return "index";
    }
}
